package com.shxy.config;

import com.shxy.ui.CommonReturn;
import lombok.extern.java.Log;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 自定义异常处理
 */
@RestControllerAdvice
@Log
public class MyControllerAdvice {

    /**
     * 自定义验证异常处理
     * @param ex
     * @param headers
     * @param status
     * @param request
     * @return
     */
    @ExceptionHandler(value = BindException.class)
    public CommonReturn handleBindException(BindException ex, HttpHeaders headers, HttpStatus status, WebRequest request){
        Map<String, String> messages = new HashMap<>();
        BindingResult result = ex.getBindingResult();
        if(result.hasErrors()){
            List<ObjectError> errors = result.getAllErrors();
            for (ObjectError error: errors) {
                FieldError fieldError = (FieldError) error;
                messages.put(fieldError.getField(), fieldError.getDefaultMessage());
            }
            log.info(messages.toString());
        }
        return CommonReturn.create(messages);
    }

    /**
     * 自定义异常处理
     * @param ex
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public CommonReturn exceptionHandler(Exception ex){
        ex.printStackTrace();
        return CommonReturn.create("fail", ex.getMessage());
    }
}
